package run.bottle.mail.handle;

import freemarker.template.Configuration;
import freemarker.template.Template;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import run.bottle.mail.model.entity.BaseResponse;
import run.bottle.mail.model.entity.Email;
import run.bottle.mail.model.enums.EmailType;

/**
 * 描述
 *
 * @author LiYuanCheng
 * @date 2020-06-05 15:08
 */
@Component
public class FreemarkerHandler implements EmailHandler {


  private static final Logger logger = LoggerFactory.getLogger(FreemarkerHandler.class);

  @Autowired
  private JavaMailSender mailSender;

  @Autowired
  public Configuration configuration;

  /**
   * 发送人
   */
  @Value("${spring.mail.username}")
  public String userName;

  @Override
  public BaseResponse send(Email mail){
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper;
    try {
      helper = new MimeMessageHelper(message, true);
      //这里可以自定义发信名称比如：爪哇笔记
      helper.setFrom(userName,"爪哇笔记");
      helper.setTo(mail.getEmail());
      helper.setSubject(mail.getSubject());
      Map<String, Object> model = new HashMap<>();
      model.put("mail", mail);
      Template template = configuration.getTemplate(mail.getTemplate());
      String text = FreeMarkerTemplateUtils.processTemplateIntoString(
          template, model);
      helper.setText(text, true);
      mailSender.send(message);
      mail.setContent(text);
    } catch (Exception e) {
      logger.error("发送失败:",e);
      return BaseResponse.ok("发送失败！");
    }
    return BaseResponse.ok("发送成功！");
  }

  @Override
  public EmailType getEmailType() {
    return EmailType.TEMPLATE;
  }
}
